package app.view.mediators
{
	import app.AppConstants;
	import app.model.flare.vos.StateVO;
	import app.view.forms.AddActionForm;
	
	import mx.core.Application;
	import mx.events.FlexEvent;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;

	public class AddActionMediator extends Mediator
	{
		public static const NAME:String = "AddActionMediator";
		
		private var source:String;
		private var application:Application;
		private var isViewCreated:Boolean;
		
		public function AddActionMediator( app:Application )	{
			application = app;
			super(NAME, new AddActionForm());
		}
		
		
		
		override public function listNotificationInterests():Array{
			return [	AppConstants.POPUP_ADD_ACTION_FORM	];
		}
		
		override public function handleNotification(note:INotification):void{
			switch(note.getName()){
				case AppConstants.POPUP_ADD_ACTION_FORM:
					source = String( note.getBody() );
					show();
					break;
			}
		}
		
		private function show():void{
			if(view.isPopUp)return;
			activate();
			PopUpManager.addPopUp( view, application, true);
			view.input.setFocus();
		}
		
		private function hide():void{
			if(!view.isPopUp)return;
			deactivate();
			PopUpManager.removePopUp( view )
		}
		
		private function positionView():void{
			view.x = application.mouseX - view.width * 0.5;
			view.y = application.mouseY - view.height * 0.5;
		}
		
		
		private function activate():void{
			if(isViewCreated){
				positionView();
				addListeners();
			}else{
				view.addEventListener(FlexEvent.CREATION_COMPLETE, onViewCreationComplete);
			}
			
		}
		
		private function onViewCreationComplete(event:FlexEvent):void{
			view.removeEventListener(FlexEvent.CREATION_COMPLETE, onViewCreationComplete);
			isViewCreated = true;
			activate();
			
		}
		
		private function deactivate():void{
			removeListeners();
			view.input.text="";
		}
		
		private function addListeners():void{
			view.input.addEventListener(FlexEvent.ENTER, onTextEnter)
		}
		
		private function removeListeners():void{
			view.input.removeEventListener(FlexEvent.ENTER, onTextEnter)
		}
		
		private function onTextEnter(event:FlexEvent):void{
			
			sendCreateAction();
			hide();
		}
		
		
		private function sendCreateAction():void{
			sendNotification(AppConstants.CREATE_NEW_ACTION, source, view.input.text)
		}
		
		private function get view():AddActionForm{
			return AddActionForm(viewComponent);
		}
		
	}
}